<template>
  <NavBar :title="title" left-arrow @click-left="handleBack" />
  <div class="chat-content" ref="chatContent">
    <div class="chat-item" v-for="item in groupChatList" :key="item._id">
      <!-- 其他用户发送的消息 -->
      <div class="message-wrapper receiver" v-if="item.senderId._id !== user.id">
        <div class="avatar">
          <img :src="item.senderId.avatar" alt="" @click="handleUserInfo(item.senderId._id)" />
        </div>
        <div class="message">{{ item.content }}</div>
      </div>
      <!-- 当前用户发送的消息 -->
      <div class="message-wrapper sender" v-else>
        <div class="message">{{ item.content }}</div>
        <div class="avatar">
          <img :src="item.senderId.avatar" alt="" @click="handleUserInfo(item.senderId._id)" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import NavBar from '@/components/NavBar.vue'
import { chatApi } from '@/api/chat'

const user = JSON.parse(localStorage.getItem('user'))

const router = useRouter()
const route = useRoute()

const roomInfo = ref({})
const memberCount = ref(0)

const chatContent = ref(null)
const chatContentHeight = ref(0)

const title = computed(() => {
  return roomInfo.value.name + ' ' + '(' + memberCount.value + ')'
})
const groupChatList = ref([])

const getRoomDetail = async () => {
  const res = await chatApi.getRoomDetail(route.params.id)
  roomInfo.value = res
  memberCount.value = roomInfo.value.members.length
}
const getGroupChatList = async () => {
  const res = await chatApi.getRoomHistory(route.params.id)
  groupChatList.value = res
}
const emit = defineEmits(['goUserInfo'])
const handleUserInfo = (id) => {
  emit('goUserInfo', id)
}
const handleBack = () => {
  router.back()
}
// 自动滚动到聊天内容的底部
const scrollToBottom = () => {
  nextTick(() => {
    // 获取聊天内容高度
    chatContentHeight.value = chatContent.value.scrollHeight
    console.log(chatContentHeight.value)
    // 滚动到底部
    chatContent.value.scrollTo({
      top: chatContentHeight.value,
      behavior: 'smooth',
    })
  })
}
onMounted(async () => {
  await getRoomDetail()
  await getGroupChatList()
  scrollToBottom()
})

defineExpose({
  getGroupChatList,
})
</script>

<style scoped>
@import '../styles/chat-detail.css';
</style>
